package com.css.fxfzmh.login.security;

import com.css.fxfzmh.util.PlatformRSAUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lixiaofeng on 2020/4/18.
 */
@Slf4j
public abstract class LoginSecretPool {
    private static final List<Map<String, String>> SECRET_POOL = new ArrayList();
    private static final int SECRET_NUM_PRODUCT_MODE = 100;

    public LoginSecretPool() {
    }

    public static Map<String, String> getKeys() {
        log.debug("密钥对数量:{}", SECRET_POOL.size());
        Object resultMap = null;
        HashMap map = new HashMap(SECRET_NUM_PRODUCT_MODE);
        map.put("privateKey", "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALQohyk0ugrBqv+kSq6BTpTIAollHiOtnPJu/Re8NxUcBC5yZx60UVrCIYRO7ujzuPGlhWfzqH/nCLMRNDIyRksmBuRey9R5qnLD8O5DabA21wamKwqI5B8GN6dWUHY+s4wTPRv510+cQ8ZB8q+Xr81boGqw82gKBNmvUoJMQt0XAgMBAAECgYAELax02DQ4a6V7qGPTCEy6RqlIZn/8c9pgBRL5qfPdGXk/WofpvmTkpfwBBZOk84ImmKAveQc/cCxTeuKrB1959Lwvfp46zxZwBJyXRD0PZYJJFFTMI7n8X4L+cuOdYG2516DYUz/DrD2gsTURdO3TeKEaaY+/Ao7Vfw4ifBLCgQJBAOUznB7UjENXnI9NXLw4Ts6Rr8384NfvrxMit4e+OJTHbVkbs9846btD8KCIof7tzHJmuEEFuu1sNvH2q9LERnMCQQDJOPhIbvUgjkWGDVt+YUYG+h/V19obtnELcOa7XE0mtH7V+P5R2IQxn1cskgaGA/ULfI2cBy4SLi84tIE38AHNAkEAxlWlqEwW4ANFWAAC2mEDWN9auS41RsaCwlVNaapifeQgrHY7bVNrdn/xDomNXPNb8jcPBD04J1F4LmNdBjKQHwJAS0hEI51XmkmAG0oOC/dKorubg37RPAMCwhwIRtqehreKqHUSeP5/Xq1ViPhM9oCughCkTlalVunugtGNcqcZlQJAMsBqfrGgUa5OHEo1Lp4apFXy/yyENJ3vWFFJhBDDQMJav+OUjxiWyjaauBAqKr7M5Y7FvyTdG+NEVaNXtNuVdQ==");
        map.put("publicKey", "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0KIcpNLoKwar/pEqugU6UyAKJZR4jrZzybv0XvDcVHAQucmcetFFawiGETu7o87jxpYVn86h/5wizETQyMkZLJgbkXsvUeapyw/DuQ2mwNtcGpisKiOQfBjenVlB2PrOMEz0b+ddPnEPGQfKvl6/NW6BqsPNoCgTZr1KCTELdFwIDAQAB");
        resultMap = map;

        log.debug("private_key:{}", ((Map)resultMap).get(PlatformRSAUtils.PRIVATE_KEY));
        log.debug("public_key:{}", ((Map)resultMap).get(PlatformRSAUtils.PUBLIC_KEY));
        return (Map)resultMap;
    }

    private static Map<String, String> getKeyMap(int secretNum) {
        Map<String, String> resultMap = null;
        if (SECRET_POOL.size() > 0) {
            resultMap = (Map)SECRET_POOL.get(getRandomNum(secretNum));
        } else {
            synchronized(SECRET_POOL) {
                if (SECRET_POOL.size() == 0) {
                    for(int i = 0; i < secretNum; ++i) {
                        try {
                            SECRET_POOL.add(PlatformRSAUtils.createKeys());
                        } catch (Exception e) {
                            log.error("生成密钥对错误:", e);
                        }
                    }
                }

                resultMap = (Map)SECRET_POOL.get(getRandomNum(secretNum));
            }
        }

        return resultMap;
    }

    private static int getRandomNum(int max) {
        return RandomUtils.nextInt(0, max);
    }
}